function makeSnug(fig)
% Make fig fit "tightly" around its children hgobjects
%   Automatically determine and set the "best" width and height for fig such that 
%   it fits tightly around its children graphics objects (extracted from fig)
%
  % Determine best dimensions given current hgobjects' extents
    objects = get(fig, 'Children');
  % Only consider visible hgobjects
    if numel(objects)==1 && ishandle(objects) && strcmp(get(objects, 'Visible'), 'on')
      % do nothing
    elseif numel(objects)==1
        return % having done nothing
    else % we have more than one object so we need to perform the visible check on cell arrays        
        objects = objects(ishandle(objects) && ...
                  cellfun(@strcmp, get(objects, 'Visible'), 'on', 'UniformOutput', false));
    end
  % Find min and max x's and y's
    positions = get(objects, 'Position');
    minx = min(positions(1));
    miny = min(positions(2));    
    extents = get(objects, 'Extent');
    maxx = max(positions(1)+extents(3));
    maxy = max(positions(2)+extents(4));
  % Calculate total extents 
    xrange = maxx - minx;
    yrange = maxy - miny;
  % Set positions
    set(objects, 'Position', [positions(1:2) xrange yrange])
    pos = get(fig, 'Position');
    set(fig, 'Position', [pos(1:2) maxx + minx maxy + miny])
end

